package cool.goodbai.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cool.goodbai.api.BaseController;
import cool.goodbai.constant.ApiConstant;
import cool.goodbai.entity.User;
import cool.goodbai.mapper.UserMapper;
import cool.goodbai.service.impl.UserServiceImpl;
import cool.goodbai.util.PageUtil;
import cool.goodbai.vo.PageResult;
import cool.goodbai.vo.Response;
import cool.goodbai.vo.UserLoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@Api(tags = "User")
@CrossOrigin
@RestController()
@RequestMapping(ApiConstant.BASE_API_URL + "/user/")
public class UserController extends BaseController {
    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "默认Get请求", notes = "请求不存在的路径时调用此默认接口")
    @ApiImplicitParam(name = "name", value = "默认字段", required = true, dataTypeClass = String.class)
    @GetMapping(value = "/{name}")
    @ResponseBody
    public String helloWorld(@PathVariable(name = "name") String name) {
        return "Hello " + name;
    }

    @ApiOperation(value = "用户登录", notes = "用户登录")
    @PostMapping(value = "/login")
    @ResponseBody
    public Response<SaTokenInfo> login(@RequestBody UserLoginVo user) {
        try {
            // 调用service层的登录逻辑查询用户是否存在
            User result = userService.login(user.getUsername(), user.getPassword());
            Optional.ofNullable(result).ifPresent(r -> {
                StpUtil.login(r.getId());
                // 使用sa-token进行登录并将session存储起来
                StpUtil.getSession().set("user", result);
            });
            // 如果sa-token登录状态为在线就返回给前端成功的响应
            if (StpUtil.isLogin()) {
                return getSuccessResult(StpUtil.getTokenInfo());
            } else {
                return getFailResult(404, "登录出现异常");
            }
        } catch (RuntimeException e) {
            return getFailResult(404, "登录失败");
        }
    }

    @ApiOperation(value = "获取当前登录用户数据", notes = "获取当前登录用户数据")
    @GetMapping(value = "/currentUser")
    @ResponseBody
    public Response<User> currentUser() {
        try {
            if (StpUtil.isLogin()) {
                return getSuccessResult(userMapper.selectByPrimaryKey(StpUtil.getSession().getModel("user", User.class).getId()));
            } else {
                return getFailResult(404, "获取登录信息异常");
            }
        } catch (RuntimeException e) {
            return getFailResult(404, "获取登录信息异常");
        }
    }

    @ApiOperation(value = "检查登录状态", notes = "检查登录状态")
    @GetMapping("isLogin")
    @ResponseBody
    public Response<String> isLogin() {
        if (StpUtil.isLogin()) {
            return getSuccessResult("当前会话已登录");
        } else {
            return getFailResult(404, "当前会话未登录");
        }
    }

    @ApiOperation(value = "退出登录", notes = "退出登录")
    @GetMapping("logout")
    @ResponseBody
    public Response<String> logout() {
        StpUtil.getSession().logout();
        StpUtil.logout();
        return getSuccessResult("退出登录");
    }

    @ApiOperation(value = "添加用户", notes = "添加用户")
    @PostMapping(value = "/insert")
    @ResponseBody
    public Response<User> insert(@NotNull @RequestBody User user) {
        try {
            User result = userService.insert(user);
            return getSuccessResult(result);
        } catch (RuntimeException e) {
            return getFailResult(404, "添加用户失败");
        }
    }

    @ApiOperation(value = "用户注册", notes = "用户注册")
    @PostMapping(value = "/register")
    @ResponseBody
    public Response<User> register(@NotNull @RequestBody User user) {
        try {
            User result = userService.register(user);
            return getSuccessResult(result);
        } catch (RuntimeException e) {
            return getFailResult(404, "添加用户失败");
        }
    }

    @ApiOperation(value = "删除用户", notes = "删除用户")
    @PostMapping(value = "/delete")
    @ResponseBody
    public Response<User> delete(@RequestParam Long id) {
        try {
            User result = userService.delete(id);
            return getSuccessResult(result);
        } catch (RuntimeException e) {
            return getFailResult(404, "删除用户失败");
        }
    }

    @ApiOperation(value = "更新用户", notes = "更新用户")
    @PostMapping(value = "/update")
    @ResponseBody
    public Response<User> update(@RequestBody User user) {
        try {
            User result = userService.update(user);
            return getSuccessResult(result);
        } catch (RuntimeException e) {
            return getFailResult(404, "更新用户失败");
        }
    }

    @ApiOperation(value = "查询用户", notes = "查询用户")
    @PostMapping(value = "/select")
    @ResponseBody
    public PageResult<List<User>> select(@RequestParam Integer current, @RequestParam Integer pageSize,
                                         @RequestParam(required = false) String username, @RequestParam(required = false) String name,
                                         @RequestParam(required = false) String phone, @RequestParam(required = false) String sex,
                                         @RequestParam(required = false) String identityNum, @RequestParam(required = false) String email,
                                         @RequestParam(required = false) String nation, @RequestParam(required = false) String politicsStatus,
                                         @RequestParam(required = false) String maritalStatus, @RequestParam(required = false) String school,
                                         @RequestParam(required = false) String major, @RequestParam(required = false) String education,
                                         @RequestParam(required = false) String access, @RequestParam(required = false) Long id) {
        try {
            PageUtil.checkPageParam(current, pageSize);
            User user = new User();
            user.setUsername(username)
                    .setName(name)
                    .setPhone(phone)
                    .setSex(sex)
                    .setIdentityNum(identityNum)
                    .setEmail(email)
                    .setNation(nation)
                    .setPoliticsStatus(politicsStatus)
                    .setMaritalStatus(maritalStatus)
                    .setSchool(school)
                    .setMajor(major)
                    .setEducation(education)
                    .setAccess(access)
                    .setId(id);
            return userService.select(user, current, pageSize);
        } catch (RuntimeException e) {
            return getFailPageResult(404, "查询用户失败" + e.getMessage());
        }
    }

    @ApiOperation(value = "查询用户（主键）", notes = "查询用户（主键）")
    @GetMapping(value = "/selectById")
    @ResponseBody
    public Response<User> selectById(@RequestParam Long id) {
        try {
            return getSuccessResult(userMapper.selectByPrimaryKey(id));
        } catch (RuntimeException e) {
            return getFailResult(404, "查询用户失败" + e.getMessage());
        }
    }
}
